package tree

// gorm scan
type Node struct {
	ID       uint   `json:"id"`       // ID
	ParentID uint   `json:"parentId"` // 上级ID
	Name     string `json:"label"`
	Children []Node `json:"children,omitempty" gorm:"-"`
}

// findChild 获取子节点
func (o *Node) findChild(data []Node) {
	for _, v := range data {
		if v.ParentID != o.ID {
			continue
		}
		v.findChild(data)
		o.Children = append(o.Children, v)
	}
}

// hasParent 判断列表中是否有父节点
func (o *Node) hasParent(data []Node) bool {
	for _, v := range data {
		if v.ID == o.ParentID {
			return true
		}
	}
	return false
}

func Build(data []Node) []Node {
	var trees []Node
	for _, v := range data {
		if v.hasParent(data) {
			continue
		}
		v.findChild(data)
		trees = append(trees, v)
	}
	return trees
}
